package cn.hnu.qq.global;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonInputStream extends BufferedInputStream {

	private ObjectInputStream input;
	
	public JsonInputStream(InputStream in) {
		super(in);
		try {
			input = new ObjectInputStream(this);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 默认json 读取最大为4096字节
	 * @return
	 * @throws IOException
	 */
	public Object readObject() throws Exception {
//		byte[] data = new byte[4096];
//		int len = super.read(data);
//		return ArrayToObject(data,len);
		return input.readObject();
	}

	protected byte[] ObjectToArray(Object obj) {
		return JSON.toJSONBytes(obj, SerializerFeature.WriteClassName);
	}

	@SuppressWarnings("unchecked")
	private Object ArrayToObject(byte[] obj, int length) {
		try {
			return JSON.parse(new String(obj, 0, length));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
